<script setup>
import OApageheader from '../../components/OApageheader.vue';
import {ref,reactive,onMounted,computed,watch} from 'vue';
import {ElMessage} from 'element-plus';
import apiClient from '../../api/api';
import OAMain from '../../components/OAMain.vue';
import OAdialog from '../../components/OAdialog.vue';
import { useAuthStore } from '../../stores/auth.js'; // 导入 auth 模块的 store

const authStore = useAuthStore(); // 获取 auth 模块的 store
const base_url = import.meta.env.VITE_BASE_URL

let staffs = ref([]); // 通知数据对象，用于存储通知数据
let pagination = reactive({ // 分页数据
  total: 1, // 总条数
  page: 1, // 当前页码
  pageSize: 5, // 每页显示条数

});

let filterForm = reactive({ // 表单数据对象，用于存储表单输入的值
  department_id: 0, // 部门ID
});

let departments = ref([]); // 部门数据对象，用于存储部门数据

let tableref = ref(); // 表格引用对象，用于操作表格

const getstaffspage = async (page,page_size) => {
  try {
    const res = await apiClient.get('staff/stafflist/', {
      params: {
        page: page,
        page_size: page_size,
      }
    });
    pagination.total = res.data.count; // 获取总条数
    staffs.value = res.data.results; 
  } catch (error) {
    ElMessage.error(error.message);
  }
};
// 监听页数
watch(() => pagination.page, async function(value) { // 监听分页数据变化
    getstaffspage(value,pagination.pageSize); // 重新获取分页数据
  });
// 监听每页显示条数
watch(() =>pagination.pageSize, function(value){ // 监听分页数据变化
    if(pagination.page == 1){ 
      getstaffspage(1,value); 
    }else{ 
      pagination.page = 1;
    }
  });

onMounted(async() => { // 页面加载时，获取通知数据
  try {
    getstaffspage(1,pagination.pageSize); // 调用分页数据函数，初始化获取第1页的数据
    let res = await apiClient.get('oaauth/dept/'); // 发送请求，获取部门数据
    departments.value = res.data; // 存储部门数据
  }catch (error) { 
      ElMessage.error(error.message); 
  }
})

const onSearch = async () => {
  try {
    pagination.page = 1; // 查询时重置为第1页
    const res = await apiClient.get('staff/stafflist/', {
      params: {
        page: pagination.page,
        page_size: pagination.pageSize,
        department_id: filterForm.department_id,
        realname: filterForm.name,
      }
    });
    pagination.total = res.data.count; // 更新分页总数
    staffs.value = res.data.results; // 更新数据
  } catch (error) {
    ElMessage.error(error.message);
  }
};


// 下载功能
const onDownload = async() => { // 提交表单
    let rows = tableref.value.getSelectionRows(); // 获取选中的行数据
    if (rows.length == 0) { // 如果没有选中行数据
      ElMessage.info('请选择要导出的员工'); 
      return; // 退出函数
    }
    // 提取 id 列表并序列化
    const ids = rows.map(row => row.id);
    const idsStr = JSON.stringify(ids);
    console.log('最终 ids：', idsStr); // 应输出 "[25]"
    try {
        const res = await apiClient.get('staff/download/', {
            params: { ids: idsStr },
            paramsSerializer: params => `ids=${encodeURIComponent(params.ids)}`,
            responseType: 'blob',
    });
        let href = URL.createObjectURL(res.data); // 创建一个指向返回的二进制的 URL
        const a = document.createElement('a'); // 创建一个 a 标签
        a.href = href; // 设置 a 标签的 href 属性为 URL
        a.download = '员工信息.xlsx'; // 设置 a 标签的 download 属性为文件名，在点击时候会自动下载
        document.body.appendChild(a); // 将 a 标签添加到文档中
        a.click(); // 触发 a 标签的点击事件，点击浏览器开始下载
        document.body.removeChild(a); // 下载完成后，从文档中移除 a 标签
        URL.revokeObjectURL(href); // 移除 URL 对象
  } catch (err) {
    ElMessage.error(err?.response?.data?.msg || err.message || '导出失败');
  }
}

// 上传成功
const onUploadSuccess = () => { 
  ElMessage.success('上传成功'); // 显示成功消息
  getstaffspage(1,pagination.pageSize); // 重新获取分页数据
}
// 上传失败
const onUploadError = (error) => { 
  console.log("当前 token:", authStore.token)

  ElMessage.error(error.response?.data?.msg || error.message || '上传失败'); // 显示错误消息
}

</script>

<template>
<OAMain>
  <OApageheader content="员工列表"></OApageheader>
  <el-card>
    <el-form :inline="true" class="my-form-inline filter-form">
        <el-form-item label="按部门">
            <el-select v-model="filterForm.department_id">
                <el-option :value="0" label="所有部门"></el-option>
                <el-option v-for="item in departments" :label="item.name" :value="item.id" :key="item.name" />
            </el-select>
        </el-form-item>
        <el-form-item label="姓名">
            <el-input v-model="filterForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item>
           <el-button type="primary" icon="Search" @click="onSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
            <el-button type="danger" icon="Download" @click="onDownload">下载</el-button>
         </el-form-item>
         <el-form-item>
            <el-upload :action="base_url + 'staff/upload/'" 
            :headers="{Authorization: 'Bearer ' + authStore.token}"
            :on-success="onUploadSuccess" 
            :on-error="onUploadError"
            :show-file-list="false" 
            :auto-upload="true"
            accept=".xlsx,.xls">
                <el-button type="danger"  icon="Upload">上传</el-button>
            </el-upload>
        </el-form-item>
    </el-form>
  </el-card>

  <el-card>
    <!-- data必须是一个数组，prop表数组的对象，label是列标题（表头） -->
  <el-table :data="staffs" style="width: 100%" ref="tableref">   
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="60">
        <template #default="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column prop="realname" label="姓名"/>
      <el-table-column prop="email" label="邮箱"/>
      <el-table-column prop="department.name" label="部门" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status ==1" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.status == 2" type="warning">未激活</el-tag>
          <el-tag v-else type="danger">已锁定</el-tag>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <template #footer>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <el-form-item>
            <el-select v-model="pagination.pageSize" size="small" style="width: 100px;">
                <el-option select label="5条/页" :value="5"></el-option>
                <el-option  label="10条/页" :value="10"></el-option>
                <el-option  label="20条/页" :value="15"></el-option>
            </el-select>
          </el-form-item>
      <el-pagination background layout="prev, pager, next" :total="pagination.total" v-model:current-page="pagination.page" :page-size="pagination.pageSize" />
        </div>
    </template>
</el-card>
    
</OAMain>


</template>

<style scoped>
.el-tag {
  margin-right: 5px;
}
.el-pagination {
  justify-content: center;
}
.filter-form {
  padding: 20px;
  margin-bottom: 20px;

  .el-form-item {
    margin-right: 30px;
    
    .el-select {
      width: 200px;
    }
  }
}
</style>
